/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
    if(matrix.length===0)return false;
    let rows = search(matrix.length, function (i) {
        return matrix[i][0];
    },target);
    let cols = [];
    if(rows[0]===rows[1]||matrix[rows[0]][0]<=target&&matrix[rows[1]][0]>target){
        cols = search(matrix[rows[0]].length, function (i) {
            return matrix[rows[0]][i];
        },target);
        cols = [matrix[rows[0]][cols[0]],matrix[rows[0]][cols[1]]];
    }else if(matrix[rows[1]][0]<=target){
        cols = search(matrix[rows[1]].length, function (i) {
            return matrix[rows[1]][i];
        },target);
        cols = [matrix[rows[1]][cols[0]],matrix[rows[1]][cols[1]]];
    }
    if(cols[0]===target||cols[1]===target){
        return true;
    }
    return false;
};
function search(length,method,target){
    let i=0,j = length-1;
    if(length===1)return [i,i];
    while(i<j-1){
        //console.log(i,j);
        let m = (i+j)/2 | 0;
        let v = method(m);
        if(v<target)
            i = m;
        else if(v>target)
            j = m;
        else{
            i =j = m;break;
        }
    }
    return [i,j];
}

var arr = [
    [1,   3,  5,  7],
    [10, 11, 16, 20],
    [23, 30, 34, 50]
];

console.log(searchMatrix(arr,22));
